"""
自动文章发送工具
主应用入口文件
"""

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
import uvicorn
from pathlib import Path

from src.core.config import get_settings
from src.core.database import init_db
from src.api import hot_trends, content_generation, publishing, tasks, config
from src.web import admin_routes

# 获取配置
settings = get_settings()

# 创建FastAPI应用
app = FastAPI(
    title="自动文章发送工具",
    description="基于AI的自动化内容创作和分发系统",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册API路由
app.include_router(hot_trends.router, prefix="/api/v1/trends", tags=["热点"])
app.include_router(content_generation.router, prefix="/api/v1/content", tags=["内容生成"])
app.include_router(publishing.router, prefix="/api/v1/publish", tags=["发布"])
app.include_router(tasks.router, prefix="/api/v1/tasks", tags=["任务"])
app.include_router(config.router, prefix="/api/v1/config", tags=["配置"])

# 注册Web管理界面路由
app.include_router(admin_routes.router, prefix="/admin", tags=["管理"])

# 静态文件服务
if Path("static").exists():
    app.mount("/static", StaticFiles(directory="static"), name="static")


@app.on_event("startup")
async def startup_event():
    """应用启动时初始化"""
    # 初始化数据库
    init_db()
    print("✅ 应用启动完成")


@app.get("/")
async def root():
    """根路径 - 重定向到管理界面"""
    return RedirectResponse(url="/admin", status_code=302)


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy"}


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower()
    )